<template>
  <div>
    <el-card class="course-list-card" shadow="hover">
      <h2 style="margin-bottom: 20px">课程列表</h2>
      <!-- 搜索框 -->
      <el-input
          v-model="searchQuery"
          placeholder="搜索课程或章节"
          clearable
          style="width: 300px; margin-bottom: 20px"
          @input="handleSearch"
          suffix-icon="el-icon-search"
      >
      </el-input>
      <!-- 课程列表 -->
      <el-table
          :data="paginatedCourses"
          border
          style="width: 100%; margin-bottom: 20px"
      >
        <el-table-column prop="course_id" label="课程ID" width="100"></el-table-column>
        <el-table-column prop="course_code" label="课程代码" width="150"></el-table-column>
        <el-table-column prop="course_name" label="课程名称"></el-table-column>
        <el-table-column prop="course_description" label="课程描述"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" @click="toggleCourseChapters(scope.row)">
              查看章节
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="filteredCourses.length"
          layout="prev, pager, next"
          style="text-align: right"
      ></el-pagination>

      <!-- 章节列表 -->
      <el-collapse v-model="activeCourses" style="margin-top: 20px">
        <el-collapse-item
            v-for="course in expandedCourses"
            :key="course.course_id"
            :title="course.course_name"
            :name="course.course_id"
        >
          <div style="margin-bottom: 10px; text-align: right">
            <el-button
                type="danger"
                @click="batchDeleteChapters(course.course_id)"
                :disabled="!selectedChapters.length"
            >
              批量删除章节
            </el-button>
            <el-button type="primary" @click="openChapterDialog(course.course_id)">
              添加章节
            </el-button>
          </div>
          <el-table
              :data="course.chapters"
              ref="chapterTable"
              style="width: 100%; margin-top: 20px"
              border
              @selection-change="handleSelectionChange"
          >
            <el-table-column
                type="selection"
                width="50"
                align="center"
            ></el-table-column>
            <el-table-column prop="chapter_id" label="章节ID" width="100"></el-table-column>
            <el-table-column prop="chapter_title" label="章节标题"></el-table-column>
            <el-table-column prop="chapter_description" label="章节描述"></el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-button size="small" @click="editChapter(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteChapter(scope.row.chapter_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>

    <!-- 添加或编辑章节的弹窗 -->
    <el-dialog :visible.sync="chapterDialogVisible" title="章节信息">
      <el-form :model="currentChapter" label-width="120px">
        <el-form-item label="章节标题">
          <el-input v-model="currentChapter.chapter_title" placeholder="请输入章节标题"></el-input>
        </el-form-item>
        <el-form-item label="章节描述">
          <el-input v-model="currentChapter.chapter_description" placeholder="请输入章节描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chapterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChapter">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ChapterManagement",
  data() {
    return {
      searchQuery: "",
      chapterDialogVisible: false,
      currentChapter: {
        chapter_id: null,
        chapter_title: "",
        chapter_description: "",
      },
      currentPage: 1,
      pageSize: 5,
      activeCourses: [],
      selectedChapters: [], // 当前选中的章节
      courses: [
        {
          course_id: "c1",
          course_code: "CS101",
          course_name: "课程 A",
          course_description: "课程 A 描述",
          chapters: [
            { chapter_id: "ch1", chapter_title: "章节 1", chapter_description: "描述 1" },
            { chapter_id: "ch2", chapter_title: "章节 2", chapter_description: "描述 2" },
          ],
        },
        {
          course_id: "c2",
          course_code: "CS102",
          course_name: "课程 B",
          course_description: "课程 B 描述",
          chapters: [
            { chapter_id: "ch3", chapter_title: "章节 3", chapter_description: "描述 3" },
            { chapter_id: "ch4", chapter_title: "章节 4", chapter_description: "描述 4" },
          ],
        },
        {
          course_id: "c3",
          course_code: "CS103",
          course_name: "课程 C",
          course_description: "课程 C 描述",
          chapters: [],
        },
      ],
    };
  },
  computed: {
    filteredCourses() {
      if (!this.searchQuery) return this.courses;
      return this.courses.filter(
          (course) =>
              course.course_name.includes(this.searchQuery) ||
              course.course_description.includes(this.searchQuery) ||
              course.chapters.some((chapter) =>
                  chapter.chapter_title.includes(this.searchQuery)
              )
      );
    },
    paginatedCourses() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.filteredCourses.slice(start, start + this.pageSize);
    },
    expandedCourses() {
      return this.courses.filter((course) =>
          this.activeCourses.includes(course.course_id)
      );
    },
  },
  methods: {
    handleSearch() {
      this.currentPage = 1;
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    toggleCourseChapters(course) {
      if (this.activeCourses.includes(course.course_id)) {
        this.activeCourses = this.activeCourses.filter(
            (id) => id !== course.course_id
        );
      } else {
        this.activeCourses.push(course.course_id);
      }
    },
    handleSelectionChange(selection) {
      this.selectedChapters = selection;
    },
    batchDeleteChapters(courseId) {
      const course = this.courses.find((c) => c.course_id === courseId);
      if (!course) return;

      this.selectedChapters.forEach((selectedChapter) => {
        course.chapters = course.chapters.filter(
            (chapter) => chapter.chapter_id !== selectedChapter.chapter_id
        );
      });

      this.selectedChapters = [];
      this.$message.success("章节批量删除成功");
    },
    openChapterDialog(courseId) {
      this.currentChapter = {
        chapter_id: null,
        chapter_title: "",
        chapter_description: "",
        course_id: courseId,
      };
      this.chapterDialogVisible = true;
    },
    editChapter(chapter) {
      this.currentChapter = { ...chapter };
      this.chapterDialogVisible = true;
    },
    deleteChapter(chapterId) {
      const course = this.courses.find((c) =>
          c.chapters.some((ch) => ch.chapter_id === chapterId)
      );
      if (course) {
        course.chapters = course.chapters.filter(
            (ch) => ch.chapter_id !== chapterId
        );
        this.$message.success("章节删除成功");
      }
    },
    saveChapter() {
      const { chapter_id, chapter_title, chapter_description, course_id } =
          this.currentChapter;

      if (!chapter_title) {
        this.$message.error("章节标题不能为空");
        return;
      }

      const course = this.courses.find((c) => c.course_id === course_id);

      if (chapter_id) {
        const chapter = course.chapters.find((ch) => ch.chapter_id === chapter_id);
        chapter.chapter_title = chapter_title;
        chapter.chapter_description = chapter_description;
      } else {
        const newChapter = {
          chapter_id: `ch${Date.now()}`,
          chapter_title,
          chapter_description,
        };
        course.chapters.push(newChapter);
      }

      this.chapterDialogVisible = false;
      this.$message.success("章节保存成功");
    },
  },
};
</script>

<style scoped>
.course-list-card {
  padding: 20px;
  margin: 20px;
}
.dialog-footer {
  text-align: right;
}
</style>
